package com.shop.service.impl;

import com.alibaba.fastjson.JSON;
import com.shop.dto.MD5;
import com.shop.dto.UserAgentUtil;
import com.shop.entity.user.User;
import com.shop.exception.TokenValidationFailedException;
import com.shop.service.TokenService;
import cz.mallat.uasparser.UserAgentInfo;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.annotation.RequestScope;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * Token管理接口相关业务服务实现
 *
 * @author hduser
 *
 */

@Service("tokenService")
public class TokenServiceImpl implements TokenService {

	private Logger logger = Logger.getLogger(TokenServiceImpl.class);

	/**
	 * 调用RedisAPI
	 */
	@Autowired
	private RedisUtil redisUtil;


	private int expire = SESSION_TIMEOUT;// 2h
	private String tokenPrefix = "token:";//统一加入 token前缀标识

	public int getExpire() {
		return expire;
	}

	public void setExpire(int expire) {
		this.expire = expire;
	}

	/***
	 * @param agent Http头中的user-agent信息
	 * @param user 用户信息
	 * @return Token格式<br/>
	 * 	PC：“前缀PC-USERCODE-USERID-CREATIONDATE-RONDEM[6位]”
	 *  <br/>
	 *  Android：“前缀MOBILE-USERCODE-USERID-CREATIONDATE-RONDEM[6位]”
	 */
	@Override
	public String generateToken(String agent, User user) {
		try {
			UserAgentInfo userAgentInfo = UserAgentUtil.getUasParser().parse(
					agent);
			StringBuilder sb = new StringBuilder();
			sb.append(tokenPrefix);//统一前缀
			if (userAgentInfo.getDeviceType().equals(UserAgentInfo.UNKNOWN)) {
				if (UserAgentUtil.CheckAgent(agent)) {
					sb.append("MOBILE-");
				} else {
					sb.append("PC-");
				}
			} else if (userAgentInfo.getDeviceType().equals("Personal computer")) {
				sb.append("PC-");
			} else {
				sb.append("MOBILE-");
			}
			sb.append(MD5.getMd5(user.getUserName(),32) + "-");//加密用户名称
			sb.append(user.getId() + "-");
			sb.append(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())
					+ "-");
			sb.append(MD5.getMd5(agent, 6));// 识别客户端的简化实现——6位MD5码

			return sb.toString();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public void save(String token, User user) {
		if (token.startsWith(tokenPrefix+"PC-")) {
			redisUtil.setStr(token,JSON.toJSONString(user),expire);
		} else {
			// 手机认证信息永不失效
			redisUtil.setStr(token, JSON.toJSONString(user));
		}
	}

	@Override
	public void delete(String token) {
		if (redisUtil.getStr(token).equals("")) {
			redisUtil.del(token);
		}
	}
}
